//
//  NovaSingleBarChartView.swift
//  DaGlass
//
//  Created by 李然 on 2023/4/4.
//

import UIKit

class NovaSingleBarDataSet: NovaBaseChartData {
    var color: UIColor = .clear
    var value: Double = 0.0
}

class NovaSingleBarChartView: NovaBarChartView {
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        drawBars(rect)
        
        drawMarkers()
    }
    
    private func drawBars(_ rect: CGRect) {
        let xCount = self.data.count
        guard xCount > 0 else { return }
        
        guard let context = UIGraphicsGetCurrentContext() else { return }
        
        context.saveGState()
        defer { context.restoreGState() }

        for (index, dataSet) in self.data.enumerated() {
            
            guard self.barRects.count > index else {
                return
            }
            let barRect = self.barRects[index]
            
            if let dataSet = dataSet as? NovaSingleBarDataSet {
                let yValue = dataSet.value
                if yValue > minYAxisValue {
                    context.setFillColor(dataSet.color.cgColor)
                    let height = (yValue - minYAxisValue)/(maxYAxisValue - minYAxisValue) * chartFrame.height
                    let rect = CGRect(x: barRect.minX, y: chartFrame.maxY - height, width: barRect.width, height: height)
                    let cornerRadii = CGSize(width: barCornerRadius, height: barCornerRadius)
                    let path = UIBezierPath.init(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: cornerRadii)
                    path.fill()
                }
            }
        }
    }
    
    private func drawMarkers() {
        guard let marker = marker, let markerIndex = markerIndex, markerIndex >= 0 else {
            return
        }
        guard self.data.count > markerIndex else {
            return
        }
        guard let context = UIGraphicsGetCurrentContext() else { return }
        
        context.saveGState()
        defer { context.restoreGState() }
        
        if let dataSet = self.data[markerIndex] as? NovaSingleBarDataSet {
            let yValue = dataSet.value
            if yValue > minYAxisValue {
                let height = (yValue - minYAxisValue)/(maxYAxisValue - minYAxisValue) * chartFrame.height
                
                let barRect = self.barRects[markerIndex]
                marker.refreshContent(entry: dataSet, index: markerIndex)
                marker.draw(context: context, point: CGPoint(x: barRect.midX, y: chartFrame.maxY - height))
            }
        }
    }
}
